//
//  RWAddressViewController.m
//  RedWine
//
//  Created by Liufangfang on 2017/1/14.
//  Copyright © 2017年 HuiBangKe. All rights reserved.
//

#import "RWAddressViewController.h"
#import "RWAddressTableViewCell.h"
#import "RWAddAddressViewController.h"

#import "RWAddressModel.h"

@interface RWAddressViewController ()<RWAddressTableViewCellDelegate>

@property (nonatomic, strong) NSMutableArray *addressModels;

@end

@implementation RWAddressViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initObjects];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [self loadDatas];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Load Datas

- (void)initObjects{
    
    _addressModels = [NSMutableArray array];
}

- (void)loadDatas{
    
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=addresslist&member_id=%@", [FTYUser sharedUser].userID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                [_addressModels removeAllObjects];
                [_addressModels addObjectsFromArray:baseModel.info];
                
                //[self setNavigation];
                //[self setAddressUI];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
            
            [self setNavigation];
            [self setAddressUI];
        } else {
            DLog(@"地址获取信息失败：%@", result);
        }
    }];
}

#pragma mark - Config UI

- (void)setNavigation{
    
    self.title = @"地址管理";
}

- (void)setAddressUI{
    
//    _addAddressTV = [[FTYTouchTableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT) style:UITableViewStylePlain];
    _addAddressTV = [[FTYTouchTableView alloc] initWithFrame:CGRectMake(0, 0, FTY_SCREEN_WIDTH, FTY_SCREEN_HEIGHT-FTY_STATUS_HEIGHT-FTY_NAVIGATION_HEIGHT-50) style:UITableViewStylePlain];
    [self.view addSubview:_addAddressTV];
    _addAddressTV.backgroundColor = [FTYColor getEEEEEEColorWithAlpha:1.];
    _addAddressTV.separatorStyle = UITableViewCellSeparatorStyleNone;
    //_addAddressTV.scrollEnabled = NO;
    _addAddressTV.dataSource = self;
    _addAddressTV.delegate = self;
    _addAddressTV.touchDelegate = self;
    //_addAddressTV.tableFooterView = [self setFooterUI];
    
    FTYButton *nextBtn = [FTYButton createButtonWithTitle:@"添加新地址" tColor:[UIColor whiteColor] fontSize:15.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.] cornerRadius:20];
    [self.view addSubview:nextBtn];
    nextBtn.frame = CGRectMake(10, FTY_SCREEN_HEIGHT-50-64, FTY_SCREEN_WIDTH-2*10, 40);
    [nextBtn addTarget:self action:@selector(addNewAddBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - Config Invoke Methods

- (UIView *)setFooterUI{
    
    UIView *footerV = [[UIView alloc] initWithFrame:self.view.bounds];
    
    FTYButton *nextBtn = [FTYButton createButtonWithTitle:@"添加新地址" tColor:[UIColor whiteColor] fontSize:15.*FTY_WIDTH_BASE backGroundColor:[FTYColor getMainColorWithAlpha:1.] cornerRadius:20];
    [footerV addSubview:nextBtn];
    [nextBtn addTarget:self action:@selector(addNewAddBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(30.*FTY_HEIGHT_BASE);
        make.left.mas_equalTo(10.*FTY_WIDTH_BASE);
        make.width.mas_equalTo(FTY_SCREEN_WIDTH - 2 * 10.*FTY_WIDTH_BASE);
        make.height.mas_equalTo(40.*FTY_HEIGHT_BASE);
    }];
    
    return footerV;
}

#pragma mark - Notification Method

#pragma mark - Notification Invoke Methods

#pragma mark - <UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _addressModels.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.*FTY_HEIGHT_BASE;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 100.*FTY_HEIGHT_BASE;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * const addressID = @"addressID";
    RWAddressTableViewCell *addressCell = [tableView dequeueReusableCellWithIdentifier:addressID];
    
    if (!addressCell) {
    
        addressCell = [[RWAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:addressID];
        addressCell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    [addressCell loadDataWithModel:_addressModels[indexPath.row]];
    addressCell.tag = indexPath.row;
    addressCell.delegate = self;
    return addressCell;
}

#pragma mark - <UITableViewDelegate>

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self defaultAddress:nil atIndex:indexPath.row];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - <FTYTouchTableViewDelegate>

#pragma mark - <RWAddressTableViewCellDelegate>
//设为默认地址
- (void)defaultAddress:(UIButton *)btn atIndex:(NSInteger)index
{
    RWAddressModel *addressModel = [RWAddressModel mj_objectWithKeyValues:_addressModels[index]];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=setdefaultaddr&address_id=%@&token=%@&member_id=%@", addressModel.address_id,[FTYUser sharedUser].userToken,[FTYUser sharedUser].userID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                for (int i=0;i< [_addressModels count];i++) {
                    NSMutableDictionary * dict = [_addressModels objectAtIndex:i];
                    NSMutableDictionary *dict1 = [dict mutableCopy];
                    if (i==index) {
                        [dict1 setObject:[NSNumber numberWithInteger:1] forKey:@"is_default"];
                    }else{
                        [dict1 setObject:[NSNumber numberWithInteger:0] forKey:@"is_default"];
                    }
                    
                    [_addressModels replaceObjectAtIndex:i withObject:dict1];
                }
                
                
                [self.addAddressTV reloadData];
                //[[FTYToastView alloc] addTitle:@"设置成功" addView:self.view];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            DLog(@"设置默认地址失败：%@", result);
        }
    }];
}
//编辑地址
- (void)editAddress:(UIButton *)btn atIndex:(NSInteger)index
{
    RWAddAddressViewController *addAddressVC = [[RWAddAddressViewController alloc] init];
    [self.navigationController pushViewController:addAddressVC animated:YES];
    RWAddressModel *addressModel = [RWAddressModel mj_objectWithKeyValues:_addressModels[index]];
    //_addressModel = [RWAddressModel mj_objectWithKeyValues:model];
    addAddressVC.mAddressModel = addressModel;
}
//删除地址
- (void)deleteAddress:(UIButton *)btn atIndex:(NSInteger)index
{
    RWAddressModel *addressModel = [RWAddressModel mj_objectWithKeyValues:_addressModels[index]];
    [FTYHTTPManager postInfoWithSubUrl:[NSString stringWithFormat:@"/shop/ybkapi.php?act=ybkapi&op=deladdr&address_id=%@&token=%@&member_id=%@", addressModel.address_id,[FTYUser sharedUser].userToken,[FTYUser sharedUser].userID] parameters:nil block:^(id result, NSError *error) {
        if (!error) {
            
            DLog(@"====%@", result);
            FTYBaseModel *baseModel = [[FTYBaseModel alloc] init];
            baseModel = [FTYBaseModel mj_objectWithKeyValues:result];
            FTYErrorInfoModel *errorInfo = [FTYErrorInfoModel mj_objectWithKeyValues:baseModel.err];
            
            if (0 == errorInfo.errorcode) {
                
                [_addressModels removeObjectAtIndex:index];
                
                [self.addAddressTV reloadData];
                [[FTYToastView alloc] addTitle:@"删除成功" addView:self.view];
            } else {
                [[FTYToastView alloc] addTitle:errorInfo.errorinfo addView:self.view];
            }
        } else {
            DLog(@"删除地址失败：%@", result);
        }
    }];
}

#pragma mark - Private Invoke Methods

- (void)addNewAddBtnAction:(UIButton *)btn{

    RWAddAddressViewController *addAddressVC = [[RWAddAddressViewController alloc] init];
    [self.navigationController pushViewController:addAddressVC animated:YES];
}


@end
